package com.xia.timer;

import com.xia.dao.article.IArticleDao;
import com.xia.domian.Article;
import com.xia.service.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时器
 */
@Slf4j
@Component
public class Timer {
    private IArticleDao articleDao;
    private IArticleService articleService;

    @Autowired
    public void setArticleService(IArticleService articleService) {
        this.articleService = articleService;
    }
    @Autowired
    public void setArticleDao(IArticleDao articleDao) {
        this.articleDao = articleDao;
    }
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Scheduled(cron="0 */10 * * * ? ")
    public void execute(){
        log.info("已进入计时器............");
        //在redis中查询文章的浏览量
        Set<String> set=redisTemplate.keys("*pageView*");
        for (String s : set) {
            Integer pageView= (Integer) redisTemplate.opsForValue().get(s);
            String[] stringIndex=s.split("_");
            //查询文章的组合类
            List<Article> articleList=articleDao.selectArticleOnId(0,Integer.valueOf(stringIndex[1]),0,0);
            if (articleList.size() != 0){
                //在redis中查询到的浏览量与文章的浏览量相加
                pageView+=articleList.get(0).getArticlePageView();
                //将相加的数据放入相应的文章中
                Article article = new Article();
                article.setArticleId(Integer.valueOf(stringIndex[1]));
                article.setArticlePageView(pageView);
                articleDao.updateArticle(article);
                //删除在redis中的key
                redisTemplate.delete(s);
            }
        }
        log.info("没有浏览量");
    }

    @Scheduled(cron = "0 30 12 * * ? ")
    private void hotList(){
        log.info("热榜开始排行");
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        List<Article> articleList=articleService.selectArticleCommentList();
        ArrayList<Article> articleArrayList = new ArrayList<>(articleList);
        listOps.leftPushAll("hotList", articleArrayList);
        log.info("热榜排行结束");
    }

}
